<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="设备编码" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="device_base_standing_book" column-name="code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="设备类型" class="clickChoose" prop="typeId">
          <el-input v-model="formData.typeName" placeholder="请选择" readonly />
          <!--          <el-select v-model="formData.typeId" filterable placeholder="请选择" clearable>-->
          <!--            <el-option-->
          <!--              v-for="item in userOptions"-->
          <!--              :key="item.typeId"-->
          <!--              :label="item.typeName"-->
          <!--              :value="item.typeId"-->
          <!--              clearable-->
          <!--            />-->
          <!--          </el-select>-->
          <a class="clickChoose_button" @click.prevent="addType">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="设备位置" prop="location">
          <el-input v-model="formData.location" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="规格型号" prop="model">
          <el-input v-model="formData.model" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="设备厂商" prop="firmName" class="clickChoose">
          <el-input v-model="formData.firmName" placeholder="请选择" readonly />
          <!--          <el-select v-model="formData.firmId" filterable clearable placeholder="请选择">-->
          <!--            <el-option-->
          <!--              v-for="item in userOptions1"-->
          <!--              :key="item.firmId"-->
          <!--              :label="item.firmName"-->
          <!--              :value="item.firmId"-->
          <!--            />-->
          <!--          </el-select>-->
          <a class="clickChoose_button" @click.prevent="addCompany">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="购买日期" prop="purchaseTime">
          <el-date-picker
            v-model="formData.purchaseTime"

            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="采购金额(元)" :min-width="SETTINGS.settings_decimalDigits_length" prop="purchaseMoney">
          <el-input v-model="formData.purchaseMoney" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="保修截止日期" prop="warrantyEndTime">
          <div class="standing-add first">
            <div class="add-input">
              <el-date-picker
                v-model="formData.warrantyEndTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择"
                :editable="false"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="使用部门" prop="realName">
          <div class="standing-add first">
            <div class="add-input">
              <el-select v-model="formData.deptId" filterable clearable placeholder="请选择">
                <el-option
                  v-for="item in userOptions3"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                />
              </el-select>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="设备负责人" prop="realName">
          <div class="standing-add first">
            <div class="add-input">
              <el-select v-model="formData.userId" filterable clearable placeholder="请选择">
                <el-option
                  v-for="item in userOptions2"
                  :key="item.userId"
                  :label="item.realName"
                  :value="item.userId"
                />
              </el-select>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="机台号" prop="machineNumber">
          <el-input v-model="formData.machineNumber" placeholder="请输入" clearable />
        </el-form-item>
        <el-divider />
        <!-- <el-form-item label="通讯协议" prop="protoName">
          <el-select v-model="formData.protoId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptions4"
              :key="item.protoId"
              :label="item.protoName"
              :value="item.protoId"
              clearable
            />
          </el-select>
        </el-form-item>
        <el-form-item label="IP" prop="ip">
          <el-input
            v-model="formData.ip"
            placeholder="请输入"
            clearable
            @input="validate($event)"
          />
        </el-form-item>
        <el-form-item label="端口号" prop="port">
          <el-input v-model="formData.port" placeholder="请输入" clearable />
        </el-form-item>
        <el-divider /> -->
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.fileUrl"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input v-model="formData.remark" maxlength="200" show-word-limit type="textarea" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="isShow" label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设备配图" class="double">
          <pictureUpload
            :file-names="formData.avatar"
            :file-real-names="formData.avatar"
            :file-urls="formData.avatarUrl"
            :row-index="1"
            single-multiple="single"
            @fileName="setFileName2"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, alleqiipType, equipCompany, userList, deptList, typeList } from '@/api/equipmentManage/baseInfo/equipmentInfo'
import addType from '../equipmentType/addType' // 设备类型详情弹窗
import addCompany from '../equipmentCompany/addCompany' // 设备厂商详情弹窗
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    const validateIP = (rule, value, callback) => {
      if (value && value.trim()) {
        const reg = /((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))/
        if (!reg.test(value)) {
          callback(new Error('IP地址错误'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const validatePort = (rule, value, callback) => {
      if (value && value.trim()) {
        const reg = /^[1-9]\d*$/
        if (!reg.test(value)) {
          callback(new Error('端口错误'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const validate_purchaseTime = (rule, value, callback) => {
      this.$refs.form.clearValidate('warrantyEndTime')
      if (value && value.trim()) {
        if (this.formData.warrantyEndTime) {
          if (this.$moment(this.formData.warrantyEndTime).isBefore(this.formData.purchaseTime)) {
            callback(new Error('购买日期不能大于保修截止日期'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const validate_warrantyEndTime = (rule, value, callback) => {
      this.$refs.form.clearValidate('purchaseTime')
      if (value && value.trim()) {
        if (this.formData.purchaseTime) {
          if (this.$moment(this.formData.warrantyEndTime).isBefore(this.formData.purchaseTime)) {
            callback(new Error('保修截止日期不能小于购买日期'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      loading: true,
      isShow: false,
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        typeId: undefined,
        createTime: undefined,
        model: undefined,
        firmId: undefined,
        purchaseTime: undefined,
        warrantyEndTime: undefined,
        deptId: undefined,
        userId: undefined,
        protoId: undefined,
        machineNumber: undefined,
        ip: undefined,
        port: undefined,
        purchaseMoney: undefined,
        updateBy: undefined,
        protoName: undefined,
        typeName: undefined,
        firmName: undefined,
        realName: undefined,
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        avatar: '',
        avatarRealName: '',
        avatarUrl: '',
        remark: undefined,
        location: undefined,
        status: '1'
      },
      foDate: {
        companyId: undefined,
        status: 1
      },
      userOptions: [],
      userOptions1: [],
      userOptions2: [],
      userOptions3: [],
      userOptions4: [],
      ids: [],
      roleOptions: [],
      inx: 1,
      rules: {
        name: [
          { required: true, message: '设备名称不能为空', trigger: 'change' }
        ],
        typeId: [
          { required: true, message: '设备类型不能为空', trigger: 'change' }
        ],
        code: [
          { required: true, message: '设备编码不能为空', trigger: 'blur' }
        ],
        ip: [
          { validator: validateIP, trigger: 'change' }
        ],
        port: [
          { validator: validatePort, trigger: 'change' }
        ],
        purchaseTime: [
          { validator: validate_purchaseTime, trigger: 'change' }
        ],
        warrantyEndTime: [
          { validator: validate_warrantyEndTime, trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getAll()
    if (!this.id) { // 没有id就是新增
      // Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
      //   this.formData[key] = this.defaultValue[key]
      // })
      this.loading = false
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  methods: {
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.formData.status += ''
        this.isShow = true
        this.loading = false
      })
    },
    getAll() {
      alleqiipType(this.foDate).then(res => {
        this.userOptions = res.data
      })
      equipCompany(this.foDate).then(res => {
        this.userOptions1 = res.data
      })
      userList(this.foDate).then(res => {
        this.userOptions2 = res.data
      })
      deptList(this.foDate).then(res => {
        this.userOptions3 = res.data
      })
      typeList(this.foDate).then(res => {
        this.userOptions4 = res.data
      })
    },
    onSubmit() {
      if (this.formData.purchaseMoney && !this.SETTINGS.reg_zero.test(this.formData.purchaseMoney)) {
        this.$message.warning('购买金额未正确填写')
        return
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    // 打开设备类型详情弹窗
    addType() {
      this.$layer.iframe({// 弹框
        content: {
          content: addType, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            typeId: this.formData.typeId ? this.formData.typeId : ''
          }// props
        },
        area: ['880px', '600px'],
        title: '请选择设备类型', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    addTypeCallBack(row) { // 设备类型弹窗关闭后赋值
      this.getAll()
      this.formData.typeId = row.id
      this.formData.typeName = row.name
    },
    addPanyCallBack(row) { // 设备厂商弹窗关闭后赋值
      this.getAll()
      this.formData.firmId = row.id
      this.formData.firmName = row.name
    },
    addCompany() {
      this.$layer.iframe({// 弹框
        content: {
          content: addCompany, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            typeId: this.formData.firmId ? this.formData.firmId : ''
          }// props
        },
        area: ['880px', '600px'],
        title: '请选择设备厂商', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    setFileName(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.fileUrl = data[2]
    },
    setFileName2(...data) {
      this.formData.avatar = data[0]
      this.formData.avatarRealName = data[1]
      this.formData.avatarUrl = data[2]
    }
  }
}
</script>

<style lang="less" scoped>
</style>
